﻿using System;
using System.IO;
using System.IO.Compression;

namespace Softio.Mscd
{
    public enum ResponseCompressionType
    {
        None,
        GZip,
        Deflate
    }

    public class CacheContent
    {
        public CacheContent(byte[] content, DateTime lastModifiedUtc)
        {
            this.Content = content;
            this.LastModifiedUtc = lastModifiedUtc;

            this.CompressDefalteContent();
            this.CompressGZipContent();
        }

        public byte[] Content { get; private set; }
        public byte[] GZip { get; private set; }
        public byte[] Deflate { get; private set; }
        public DateTime LastModifiedUtc { get; set; }

        private void CompressDefalteContent()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                using (DeflateStream deflate = new DeflateStream(mem, CompressionMode.Compress))
                {
                    deflate.Write(this.Content, 0, this.Content.Length);
                    deflate.Close();
                    this.Deflate = mem.ToArray();
                }
            }
        }

        private void CompressGZipContent()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(mem, CompressionMode.Compress))
                {
                    gzip.Write(this.Content, 0, this.Content.Length);
                    gzip.Close();
                    this.GZip = mem.ToArray();
                }
            }
        }

        public byte[] GetContentByType(ResponseCompressionType compressionType)
        {
            switch (compressionType)
            {
                default:
                case ResponseCompressionType.None:
                    return this.Content;
                case ResponseCompressionType.GZip:
                    return this.GZip;
                case ResponseCompressionType.Deflate:
                    return this.Deflate;
            }
        }
    }
}
